package centerberg.engine;
import java.awt.event.*;

import java.util.ArrayList;
import java.util.Collection;

import javax.swing.*;
/**
 * A class for creating a simple menu UI 
 * 
 *	@author Linus Centerström
 */

public class Menu extends JPanel implements KeyListener{
	ArrayList<MenuItem> items;
	private int selectedItem;
	private int numberOfItems;

	private Menu() {
		super();
		items = new ArrayList<MenuItem>();
		selectedItem = 0;
		numberOfItems = 0;
		addKeyListener(this);
		setFocusable(true);
		setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
	}
	
	/**
	 * Create a new Menu consisting of a MenuItem mi 
	 * @param mi The MenuItem the new Menu consists of
	 */
	
	public Menu(MenuItem mi) {
		this();
		addMenuItem(mi);
		items.get(selectedItem).select(true);
	}
	
	/**
	 * Create a Menu from a collection
	 * of MenuItems
	 * @param items The collection of items the new Menu will include
	 */
	
	public Menu(Collection<MenuItem>items) {
		this();
		addAllItems(items);
		this.items.get(selectedItem).select(true);
	}
	
	/**
	 * Add all items in the MenuItem Collection 
	 * to the Menu
	 * @param items The Collection of MenuItems to add
	 */
	
	public void addAllItems(Collection<MenuItem>items) {
		for(MenuItem mi : items) 
			addMenuItem(mi);		
	}
	
	/**
	 * Add a MenuItem to the menu
	 * @param mi the MenuItem to add
	 */
	
	public void addMenuItem(MenuItem mi) {
		items.add(mi);
		add(mi);
		numberOfItems++;
	}

	@Override
	public void keyTyped(KeyEvent e) {
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		
	}
	
	protected void enterPressed() {
		items.get(selectedItem).performAction();
	}

	@Override
	
	public void keyReleased(KeyEvent e) {
		int keyPressed = e.getKeyCode();
		if (keyPressed == KeyEvent.VK_ENTER) {
			enterPressed();
		}
		else if(keyPressed  == KeyEvent.VK_DOWN) {
			if(selectedItem == numberOfItems - 1) 
				select(0);
			else
				select(selectedItem + 1);
		}
		else if(keyPressed  == KeyEvent.VK_UP) {
			if(selectedItem == 0) 
				select (numberOfItems - 1);
			else
				select(selectedItem - 1);
		}
	}
	private void select(int i) {
		items.get(selectedItem).select(false);
		selectedItem = i;
		items.get(selectedItem).select(true);
		repaint();
	}
}
